package com.ecp.commons.task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

public class TaskServer {

	private static TaskServer		server;
	private static List<Task>		taskList;
	private static ExecutorService	pool;
	private static final int		poolsize	= 10;
	private static Logger			log			= Logger.getLogger(TaskServer.class);

	private TaskServer() {
		taskList = new ArrayList<Task>();
		pool = Executors.newFixedThreadPool(poolsize);
		new Thread() {
			public void run() {
				log.info("Start task server with " + poolsize + " threads.");
				for (;;) {
					final Task o = server.dispatch();
					pool.execute(new Thread() {
						public void run() {
							try {
								o.execute();
							} catch (Exception e) {
								e.printStackTrace();
								log.info(e.getMessage());
							}
						}
					});
				}
			}
		}.start();
	}

	public synchronized static TaskServer getInstance() {
		if (server == null) {
			server = new TaskServer();
		}
		return server;
	}

	public synchronized void append(Task o) {
		taskList.add(o);
		this.notifyAll();
	}

	public synchronized void insert(Task o) {
		taskList.add(0, o);
		this.notifyAll();
	}

	private synchronized Task dispatch() {
		while (taskList.size() == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return taskList.remove(0);
	}
}
